package cn.wen.eeayjoke.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.wen.core.permission.Permission;
import cn.wen.core.permission.PermissionListener;
import cn.wen.core.permission.XPermission;
import cn.wen.core.titlebar.DefTitleBar;
import cn.wen.core.titlebar.TitleBarUtil;
import cn.wen.core.ui.AppActivity;
import cn.wen.eeayjoke.R;
import cn.wen.eeayjoke.app.InitService;
import cn.wen.eeayjoke.entity.bean.home.AdvBean;
import cn.wen.eeayjoke.entity.bean.home.AdvertisementsBean;
import cn.wen.eeayjoke.presenter.SplashPresenter;
import cn.wen.eeayjoke.presenter.observer.QuickObserver;
import cn.wen.eeayjoke.ui.home.HomeActivity;
import cn.wen.eeayjoke.utils.CountDownHelper;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 启动页面
 */

public class WelcomeActivity extends AppActivity {

    @BindView(R.id.iv_splash)
    ImageView mIvSplash;
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;
    @BindView(R.id.rl_splash)
    RelativeLayout mRlSplash;
    private SplashPresenter mPresenter;
    // 广告对象
    private AdvBean mAdv;

    private CountDownHelper mCountDownHelper;
    private boolean isOpen;
    Bitmap mBitmap;

    @Override
    protected Object getContentLayout() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        /*防止首次安装点击home键重新实例化*/
        if (!this.isTaskRoot()) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                    finish();
                    return;
                }
            }
        }
        // 将状态栏设置为透明
        TitleBarUtil.setStatusBarColor(this);
        // 设置不能返回
        setSwipeBackEnable(false);
        // 启动服务，去初始化其它的东西
        InitService.init(this);
        mPresenter = new SplashPresenter();
    }

    @Override
    public void initNet() {
        // 1. 请求启动页面广告的接口
        requestAdv();
        // 2. 缓迟1.5秒到首页
        mIvSplash.postDelayed(new Runnable() {
            @Override
            public void run() {
                countdown();
            }
        }, 1000);

    }

    /**
     * 请求启动页面广告的接口
     */

    private void requestAdv() {
        // 1. 请求启动页面广告的接口
        mPresenter.adsListForGroupId(new QuickObserver<AdvertisementsBean>(getAppActivity()) {
            @Override
            public void onResponse(AdvertisementsBean data) {
                if (data != null) {
                    List<AdvBean> items = data.items;
                    if (items != null && items.size() > 0) {
                        mAdv = items.get(0);
                    }
                }
            }
        });
    }

    /**
     * 开启倒计时
     */
    private void countdown() {
        XPermission.with(getAppActivity())
                .permissions(Permission.STORAGE)
                .request(new PermissionListener() {
                    @Override
                    public void onSucceed() {
                        // 没有广告数据
                        if (mAdv == null) {
                            toMain();
                            return;
                        }
                        loadImage();
                    }

                    @Override
                    public void onFailed(boolean isCue) {
                        toMain();
                    }
                });


    }


    private void loadImage() {
        // 1. 网络加载
        Observable.just(mAdv.adFile)
                .flatMap(new Function<String, ObservableSource<Bitmap>>() {
                    @Override
                    public ObservableSource<Bitmap> apply(String s) throws Exception {
                        try {
                            Bitmap mBitmap = Glide.with(getAppActivity())
                                    .asBitmap()
                                    .load(s)
                                    .submit(1080, 1920)
                                    .get();
                            // 缓存Bitmap
                            if (mBitmap != null) {
                                return Observable.just(mBitmap);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        mBitmap = bitmap;
                        countDown(bitmap);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        toMain();
                    }
                });
        // 超过2秒图片没加载好就走
        Observable.timer(2, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (mBitmap == null) {
                    toMain();
                }
            }
        });

    }


    /**
     * 开启倒计时
     */
    private void countDown(final Bitmap bitmap) {
        if (isOpen || bitmap == null) {
            return;
        }
        mCountDownHelper = new CountDownHelper(4);
        mCountDownHelper.setDownListener(new CountDownHelper.OnCountDownListener() {
            @Override
            public void onCountdown(long time) {
                mTvCancel.setText("跳过" + time + "s");
            }

            @Override
            public void onComplete() {
                toMain();
            }

            @Override
            public void onStart() {
                mRlSplash.setVisibility(View.VISIBLE);
                mIvSplash.setImageBitmap(bitmap);
                mIvSplash.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toMain();
                    }
                });
            }

        });
        mCountDownHelper.start();
    }

    /**
     * 打开到首页
     */
    private void toMain() {
        if (isOpen) {
            return;
        }
        isOpen = true;
        if (mCountDownHelper != null) {
            mCountDownHelper.cancel();
            mCountDownHelper = null;
        }
        mIvSplash = null;
        mRlSplash = null;
        Intent intent = new Intent(getAppActivity(), HomeActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void initTitle(DefTitleBar titleBar) {

    }

    @Override
    protected boolean isNeedTitle() {
        return false;
    }

}
